package com.guo.pet_store.admin.controller;

import com.guo.pet_store.admin.pojo.Pet;
import com.guo.pet_store.admin.service.PetService;
import com.guo.pet_store.admin.service.TypeService;
import com.guo.pet_store.admin.service.UploadService;
import org.dom4j.rule.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;

@Controller
@RequestMapping("/admin")
public class PetController {

    @Autowired
    PetService petService;
    @Autowired
    TypeService typeService;
    @Autowired
    UploadService uploadService;
    @GetMapping("/pets")
    public String getPets(@PageableDefault(sort = {"onSale","saleDate","deleteDate"},direction = Sort.Direction.DESC,size = 20) Pageable pageable, Model model){
        model.addAttribute("page",petService.listPets(pageable));
        model.addAttribute("types",typeService.listType());
        return "admin/pets";
    }
    @GetMapping("/petInput")
    public String getPetInput(Model model){
        model.addAttribute("types",typeService.listSonType());
        return "admin/pet-input";
    }
    @PostMapping("/addPet")
    public String addPet(Pet pet, RedirectAttributes redirectAttributes, @RequestParam("picture")MultipartFile multipartFile){
        //上传图片
        pet.setSaleDate(new Date());
        pet.setOnSale(true);
        String imagePath = uploadService.uploadImage(multipartFile);
        pet.setImagePath(imagePath);
        if (petService.addPet(pet) == null){
            redirectAttributes.addFlashAttribute("error","添加失败");
        }else {
            redirectAttributes.addFlashAttribute("message","添加成功");
        }
        return "redirect:/admin/pets";
    }
    @GetMapping("/editPet/{id}")
    public String editPet(@PathVariable(value = "id") Long id,Model model){
        Pet onePet = petService.getOnePet(id);
        model.addAttribute("types",typeService.listSonType());
        model.addAttribute("pet",onePet);
        return "admin/pet-input";
    }

    @GetMapping("/delete/{id}")
    public String deletePet(@PathVariable(value = "id") Long id,RedirectAttributes redirectAttributes){
        petService.deleteAPet(id);
        redirectAttributes.addFlashAttribute("message","下架成功");
        return "redirect:/admin/pets";
    }


}
